﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace Zeus.DataTrans.Serialize.String
{
    public static class StringSerializer
    {
        private const string xmlnsString =
            "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"";

        private const string headerString = "<?xml version=\"1.0\" encoding=\"utf-16\"?>";

        /// <summary>
        /// Serialize an object to a string.
        /// </summary>
        public static string SerializedToString<T>(T serializableObject)
        {
            if (serializableObject.Equals(default(T))) return string.Empty;
            try
            {
                var serializer = new XmlSerializer(typeof(T));
                using (var stringWriter = new StringWriter())
                {
                    serializer.Serialize(stringWriter, serializableObject);
                    var str = stringWriter.ToString();
                    return str.Replace(xmlnsString, "{1}").Replace(headerString, "{0}").Replace("\r\n", string.Empty);
                }
            }
            catch (Exception ex)
            {
                return string.Empty;
            }
        }

        /// <summary>
        /// Deserialize an string into an object
        /// </summary>

        public static T DeSerializeFromString<T>(string serializedObject)
        {
            if (string.IsNullOrWhiteSpace(serializedObject)) return default(T);
            try
            {

                var stringReader = new StringReader(string.Format(serializedObject, headerString, xmlnsString));
                var serializer = new XmlSerializer(typeof(T));
                return (T)serializer.Deserialize(stringReader);
            }
            catch (Exception exception)
            {
                return default(T);
            }
        }
    }
}
